package org.ttitfly.ttcore.web.account;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.ttitfly.ttcore.entity.account.Authority;
import org.ttitfly.ttcore.entity.account.Resource;
import org.ttitfly.ttcore.entity.account.Role;
import org.ttitfly.ttcore.entity.menu.SystemMenu;
import org.ttitfly.ttcore.service.ServiceException;
import org.ttitfly.ttcore.service.account.AccountManager;
import org.ttitfly.ttcore.service.account.ResourceManager;
import org.ttitfly.ttcore.service.account.RoleManager;
import org.ttitfly.ttcore.service.menu.SystemMenuManager;
import org.ttitfly.ttcore.so.account.RoleSO;
import org.ttitfly.ttcore.util.annotation.IsSearchObject;
import org.ttitfly.ttcore.util.annotation.PageSize;
import org.ttitfly.ttcore.util.tree.TreeNode;
import org.ttitfly.ttcore.web.CrudActionSupport;

/**
 * 角色管理Action.
 * 
 * 演示不分页的简单管理界面.
 * 
 * @author calvin
 */
public class RoleAction extends CrudActionSupport<Role> {

	private static final long serialVersionUID = -4052047494894591406L;

	private AccountManager accountManager;

	//-- 页面属性 --//
	private Long id;
	private Role entity;
	private List<Role> allRoleList;//角色列表
	private List<Long> checkedAuthIds;//页面中钩选的权限id列表
	
	
	@PageSize(value = 20, exportLimit = 2000)
    private RolePageList pageList;

    @IsSearchObject
    private RoleSO roleSO;
	
    @javax.annotation.Resource
	private RoleManager roleManager;
    
    @Autowired
	private SystemMenuManager systemMenuManager;
    
    @Autowired
	private ResourceManager resourceManager;
    
    //tree
    TreeNode menuTreeRoot;
	List<String> menuTree = new ArrayList<String>();
	
	TreeNode resourceTreeRoot;
	List<String> resourceTree = new ArrayList<String>();
	

	//-- ModelDriven 与 Preparable函数 --//
	public Role getModel() {
		return entity;
	}

	public void setId(Long id) {
		this.id = id;
	}
	
	public RolePageList getPageList() {
		pageList = new RolePageList(roleSO, roleManager);
		return pageList;
	}

	public void setPageList(RolePageList pageList) {
		this.pageList = pageList;
	}

	public RoleSO getRoleSO() {
		return roleSO;
	}

	public void setRoleSO(RoleSO roleSO) {
		this.roleSO = roleSO;
	}

	public RoleManager getRoleManager() {
		return roleManager;
	}

	public void setRoleManager(RoleManager roleManager) {
		this.roleManager = roleManager;
	}

	public void prepare() throws Exception {
		if (id != null) {
			entity = accountManager.getRole(id);
		} else {
			entity = new Role();
		}
	}

	//-- CRUD Action 函数 --//
	@Override
	public String list() throws Exception {
		return SUCCESS;
	}
	
	public String preCreate() throws Exception{
		return SUCCESS;
	}
	
	public void  validateCreate() throws Exception {
		if(StringUtils.isNotBlank(entity.getName())){
			Role role = roleManager.findRoleByName(entity.getName());
			if(role != null){
				this.addFieldError("entity.name", this.getText("role.name.duplicate"));
			}
		}
	}
	public String create() throws Exception{
		roleManager.saveRole(entity);
		return SUCCESS;
	}
	
	public String preEdit() throws Exception{
		return SUCCESS;
	}
	public void  validateEdit() throws Exception {
		if(StringUtils.isNotBlank(entity.getName())){
			Role role = roleManager.findRoleByName(entity.getName());
			if(role != null){
				this.addFieldError("entity.name", this.getText("role.name.duplicate"));
			}
		}
	}
	public String edit() throws Exception{
		roleManager.saveRole(entity);
		return SUCCESS;
	}
	

	
	@Override
	public String delete() throws Exception {
		try {
			entity.setMenus(new ArrayList<SystemMenu>());
			entity.setResources(new ArrayList<Resource>());
			roleManager.deleteRole(entity);
			addActionMessage("删除角色成功");
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionMessage("删除角色失败");
		}
		return SUCCESS;
	}
	
	public String preAssignMenuAndResource2Role() throws Exception{
		menuTreeRoot = new TreeNode("0" , "菜单列表");
		resourceTreeRoot = new TreeNode("0","资源列表");
		
		List<String> selectedMenuIds = new ArrayList<String>();
		List<SystemMenu> selectedMenus = entity.getMenus();
		if(selectedMenus != null && selectedMenus.size()>0){
			for(SystemMenu selectedMenu : selectedMenus){
				selectedMenuIds.add(""+selectedMenu.getId());
			}
		}
		menuTree = systemMenuManager.findAllCheckedNode(selectedMenuIds);
		
		List<String> selectedResourceIds = new ArrayList<String>();
		List<Resource> selectedResources = entity.getResources();
		if(selectedResources != null && selectedResources.size()>0){
			for(Resource res : selectedResources){
				selectedResourceIds.add(""+res.getId());
			}
		}
		resourceTree = resourceManager.findAllCheckedNode(selectedResourceIds);
//		List<SystemMenu> list = systemMenuManager.findBy("parentId", 0L,"id",true);
//		List<TreeNode> children = new ArrayList<TreeNode>();
//		for(SystemMenu menu : list){
//			TreeNode node = new TreeNode(""+menu.getId(),menu.getTitle());
//			children.add(node);
//		}
//		menuTreeRoot.setChildren(children);
//		for(SystemMenu menu : list){
//			menuTree.add(menu.getTitle());
//		}
		return SUCCESS;
	}
	
	public String assignMenuAndResource2Role() throws Exception{
		List<Long> menuIds = new ArrayList<Long>();
		for(String strMenuId : menuTree){
			menuIds.add(Long.parseLong(strMenuId));
		}
		List<SystemMenu> menus = systemMenuManager.getByIds(menuIds);
		entity.setMenus(menus);
		
		List<Long> resourceIds = new ArrayList<Long>();
		for(String strResourceId : resourceTree){
			resourceIds.add(Long.parseLong(strResourceId));
		}
		List<Resource> resources = resourceManager.getByIds(resourceIds);
		entity.setResources(resources);
		roleManager.saveRole(entity);
		return SUCCESS;
	}

	//-- 页面属性访问函数 --//
	/**
	 * list页面显示所有角色列表.
	 */
	public List<Role> getAllRoleList() {
		return allRoleList;
	}

	/**
	 * input页面显示所有授权列表.
	 */
	public List<Authority> getAllAuthorityList() {
		return accountManager.getAllAuthority();
	}

	/**
	 * input页面显示角色拥有的授权.
	 */
	public List<Long> getCheckedAuthIds() {
		return checkedAuthIds;
	}

	/**
	 * input页面提交角色拥有的授权.
	 */
	public void setCheckedAuthIds(List<Long> checkedAuthIds) {
		this.checkedAuthIds = checkedAuthIds;
	}

	
	public TreeNode getMenuTreeRoot() {
		return menuTreeRoot;
	}

	public void setMenuTreeRoot(TreeNode menuTreeRoot) {
		this.menuTreeRoot = menuTreeRoot;
	}

	public List<String> getMenuTree() {
		return menuTree;
	}

	public void setMenuTree(List<String> menuTree) {
		this.menuTree = menuTree;
	}

	@Autowired
	public void setAccountManager(AccountManager accountManager) {
		this.accountManager = accountManager;
	}

	@Override
	protected void prepareModel() throws Exception {
		// TODO Auto-generated method stub
		
	}

	public Role getEntity() {
		return entity;
	}

	public void setEntity(Role entity) {
		this.entity = entity;
	}

	public Long getId() {
		return id;
	}
	
	public TreeNode getResourceTreeRoot() {
		return resourceTreeRoot;
	}

	public void setResourceTreeRoot(TreeNode resourceTreeRoot) {
		this.resourceTreeRoot = resourceTreeRoot;
	}
	
	public List<String> getResourceTree() {
		return resourceTree;
	}

	public void setResourceTree(List<String> resourceTree) {
		this.resourceTree = resourceTree;
	}

	//====not use
	@Override
	public String input() throws Exception {
//		checkedAuthIds = entity.getAuthIds();
		return INPUT;
	}

	@Override
	public String save() throws Exception {
		return RELOAD;
	}
	
}